#version 130

in vec2 PaperPosition;
in vec2 TexCoord;
in vec4 ProjectedPos;
in vec3 LightDirection;
in vec3 EyeDirection;
in vec3 Normal;
in vec4 MVPosition;

uniform sampler2D TexDiffuse;
uniform sampler2D TexBurnt;
uniform sampler2D TexState;
uniform sampler2D TexDepthFake;
uniform sampler2D TexDepthReal;

void main (void)  
{
  const float maxStateLimit = 1;
  vec3 diffuse = vec3(texture2D(TexDiffuse, TexCoord));
  vec3 burnt = vec3(texture2D(TexBurnt, TexCoord));
  float State = float(texture2D(TexState, TexCoord));
  //State = 0.f;
  
  float debugFactor = 0.0f;
  
  vec4 normalizedPos = ProjectedPos / ProjectedPos.w;
  vec2 screenCoord = (normalizedPos.xy + vec2(1, 1)) / 2.0;

  float fakeDepth = 1.0 / float(texture2D(TexDepthFake, screenCoord));
  float realDepth = 1.0 / float(texture2D(TexDepthReal, screenCoord));
  //if( abs(realDepth - fakeDepth) >= 0.01)
    //debugFactor = 10000.f;
	//discard;
  
  vec3 fvLightDirection = normalize(LightDirection);
  vec3 fvNormal = normalize(Normal);
  float fNDotL = dot( fvNormal, fvLightDirection );
  
  vec3 fvReflection     = normalize( ( ( 2.0 * fvNormal ) * fNDotL ) - fvLightDirection ); 
  vec3 fvViewDirection = normalize(EyeDirection);
  float fRDotV           = max( 0.0, dot( fvReflection, fvViewDirection ) );

  vec4  fvBaseColor      =  vec4(State * burnt + (maxStateLimit - State) * diffuse, 0) / maxStateLimit;

  vec4  fvTotalAmbient   = vec4(0.1, 0.1, 0.1, 0); 
  vec4  fvTotalDiffuse   = fvBaseColor * fNDotL; 
  vec4  fvTotalSpecular  = vec4(1,1,1,1) * ( pow( fRDotV, 20 ) );
  
  //gl_FragColor = vec4(screenCoord.xy, 0, 1);
  //gl_FragColor = vec4(1,1,1,1)*State;
  gl_FragColor = fvTotalAmbient + fvTotalDiffuse;
  // + vec4(1,0,0,0) * debugFactor; // + fvTotalSpecular;
  //gl_FragColor = vec4(1,1,1,1) * realDepth;
  //gl_FragColor = vec4(1,1,1,1) / ProjectedPos.z;
  //gl_FragColor = vec4(0.5, 0.0, 0.0, 0.1) + vec4(0.0, 0.5, 0.0, 0.0) * storedDepth;
  //gl_FragColor.x *= debugFactor;
}  